<?php
namespace app\lib\baidu;
use think\Db;

class Tongyi 
{

    public function chat($api_url,$api_param,$messages){
        $params = [
            'model'=>$api_param['model'],
            'input'=>[
                'messages'=>$messages
            ]
        ];
        // dump($params);die;
        $result = httpRequest($api_url,json_encode($params,JSON_UNESCAPED_UNICODE),'POST',[
            'Content-Type:application/json',
            'Authorization:Bearer '.$api_param['api_key']
        ]);
        $result = json_decode($result,true);
        if (!empty($result['output']['text'])) {
            return ['status'=>1,'answer'=>$result['output']['text']];
        }else{
            return ['status'=>0,'msg'=>$result['message']];
        }
    }

    public function farui($api_url,$messages,$api_param){
        $params = [
            'input'=>$messages,
            'appId'=>$api_param['appId'],
            'appKey'=>$api_param['appKey'],
            'timestamp'=>time().'000',
            'random'=>rand(100000,999999),
            'bizId'=>uuidCreate(),
        ];
        $params['signature'] = md5($params['appId'].$params['appKey'].$params['timestamp'].$params['random'].$api_param['appSecret']);

        do {
            $result = httpRequest($api_url,json_encode($params,JSON_UNESCAPED_UNICODE),'POST',[
                'Content-Type: application/json'
            ]);
            $result = json_decode($result,true);
            if ($result['message'] != 'waiting') {
                sleep(1);
            }
        } while ($result['code']==200 && $result['data']['output']['finish_status']==false);

        if ($result['code'] == 200 && !empty($result['data']['output']['text'])) {
            return ['status'=>1,'answer'=>$result['data']['output']['text']];
        }else{
            return ['status'=>0,'msg'=>$result['message']];
        }
    }

    public function faruiSse($api_url,$messages,$api_param){
        $params = [
            'input'=>$messages,
            'appId'=>$api_param['appId'],
            'appKey'=>$api_param['appKey'],
            'timestamp'=>time().'000',
            'random'=>rand(100000,999999),
            'bizId'=>$api_param['uuid'],
        ];
        $params['signature'] = md5($params['appId'].$params['appKey'].$params['timestamp'].$params['random'].$api_param['appSecret']);

        $result = httpRequest($api_url,json_encode($params,JSON_UNESCAPED_UNICODE),'POST',[
            'Content-Type: application/json'
        ]);
        $result = json_decode($result,true);

        if ($result['code'] == 200) {
            return ['status'=>1,'answer'=>$result['data']['output']['text'],'is_finish'=>$result['data']['output']['finish_status'] ? 1 : 0];
        }else{
            return ['status'=>0,'msg'=>$result['message']];
        }
    }

}
